# This file contains the fastlane.tools configuration
# You can find the documentation at https://docs.fastlane.tools

# For a list of all available actions, check out
#     https://docs.fastlane.tools/actions

# For a list of all available plugins, check out
#     https://docs.fastlane.tools/plugins/available-plugins

# Disable auto-updating
# update_fastlane

default_platform(:android)

# Method to update .env with the appropriate values based on environment
def set_environment_values(url, init_token, sentry_dsn)
    Dir.chdir("..") do
      env_file_path = "../.prod.env"
      content = File.read(env_file_path)

    updated_content = "ENVIRONMENT=production\nENVIRONMENT_DEBUG=debug\n" + content
    updated_content = updated_content
                        .gsub(/^BASE_URL=.*/, "BASE_URL=#{url}")
                        .gsub(/^INIT_TOKEN=.*/, "INIT_TOKEN=#{init_token}")
                        .gsub(/^SENTRY_DSN=.*/, "SENTRY_DSN=#{sentry_dsn}")

    File.write(env_file_path, updated_content)
  end
end

platform :android do
  desc "Runs all the tests"
  lane :test do
    gradle(task: "test")
  end

  desc "Submit a new beta build to Google Play"
  lane :beta do
    sh "flutter build apk --flavor prod --release --dart-define-from-file=../../.prod.json"
    upload_to_play_store(
      track: 'internal',
      apk: '../build/app/outputs/flutter-apk/app-prod-release.apk',
      json_key: 'fastlane/keys/google-play-api-key.json',
      skip_upload_metadata: true,
      skip_upload_images: true,
      skip_upload_screenshots: true,
      skip_upload_changelogs: false,
      release_status: "draft",
    )
  end

  desc "Promote beta track to prod"
  lane :promote_to_production do
    upload_to_play_store(
      track: 'beta',
      track_promote_to: 'production',
      json_key: 'fastlane/keys/google-play-api-key.json',
      skip_upload_metadata: true,
      skip_upload_images: true,
      skip_upload_screenshots: true,
      skip_upload_changelogs: false,
      release_status: "draft",
    )
  end

  desc "Submit a new production build to Google Play"
  lane :production do
    sh "flutter build apk --flavor prod --release --dart-define-from-file=../../.prod.json"
    upload_to_play_store(
      track: 'production',
      apk: '../build/app/outputs/flutter-apk/app-prod-release.apk',
      json_key: 'fastlane/keys/google-play-api-key.json',
      skip_upload_metadata: true,
      skip_upload_images: true,
      skip_upload_screenshots: true,
      skip_upload_changelogs: false,
      release_status: "draft",
    )
  end
end
